package com.tingyuge.base.jdk.io.nio.select;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @author xiaodao
 * @version 1.0
 * @description
 */
public class SelectDemo1 {
    public static void main(String[] args) throws Exception {
        //1.获取选择器
        Selector selector = Selector.open();
        //创建通道
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //非阻塞
        serverSocketChannel.configureBlocking(false);
        //绑定连接
        serverSocketChannel.bind(new InetSocketAddress(9999));
        //注册到选择器
        SelectionKey selectionKey = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        //查询已经就绪的通道操作
        Set<SelectionKey> selectionKeySet = selector.selectedKeys();
        Iterator<SelectionKey> iterator = selectionKeySet.iterator();
        while (iterator.hasNext()) {
            SelectionKey key = iterator.next();
            //判断key的就绪状态
            if (key.isAcceptable()) {

            } else if (key.isConnectable()) {

                // a connection was established with a remote server.

            } else if (key.isReadable()) {

                // a channel is ready for reading

            } else if (key.isWritable()) {

                // a channel is ready for writing

            }
            iterator.remove();
        }
    }
}
